<template>
  <transition name="toast">
    <div :class="['c-martin__toast',
      {'c-martin__toast--error': type === 'error',
      'c-martin__toast--success': type === 'success'}]"
      v-if="show">
      <div class="c-martin__toast__icon">
      </div>
      {{message}}
    </div>
  </transition>
</template>

<script>
export default {
  name: 'MartinToast',
  data() {
    return {
      show: false,
      message: '',
      type: '',
      duration: 3000
    }
  },
  methods: {
    async hide(data) {
      if (typeof data === 'object') await this.getOption(data)
      if (this.duration) {
        const timer = setTimeout(val => {
          clearTimeout(timer)
          this.show = false
          this.$el.addEventListener('transitionEnd', this.destoryEl)
        }, this.duration)
      }
    },
    destoryEl() {
      this.$el.parentNode.removeChild(this.$el)
    },
    getOption(data) {
      if (data.hasOwnProperty('duration')) {
        this.duration = data.duration
      }
      if (data.hasOwnProperty('type')) {
        this.type = data.type
      }
    },
    error(option) {
      this.type = 'error'
      this.message = typeof option === 'object' ? option.message : option
      this.show = true
      this.hide(option)
    },
    success(option) {
      this.type = 'success'
      this.message = typeof option === 'object' ? option.message : option
      this.show = true
      this.hide(option)
    },
    beforeDestory() {
      this.$el.removeEventListener('transitionEnd', this.destoryEl)
    }
  }
}
</script>
